package com.example.framework;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class HelperWithWebDriverBase extends HelperBase {


	protected static WebDriver driver;

	public HelperWithWebDriverBase(ApplicationManager manager) {
		super(manager);
		driver = manager.getWebDriverHelper().getDriver();
	}

	protected Random rnd = new Random();

	protected void submitCreation() {
		click(By.name("submit"));
	}

	protected void submitModification() {
		click(By.name("update"));
	}

	public WebElement findElement(By locator) {
		try {
			return driver.findElement(locator);
		} catch (Exception e) {
			return null;
		}
		
	}

	public List<WebElement> findElements(By locator) {
		return driver.findElements(locator);
	}

	protected void enter(By locator, String data) {
		findElement(locator).clear();
		findElement(locator).sendKeys(data);
	}

	public void select(By locator, String optionText) {
		new Select(findElement(locator)).selectByVisibleText(optionText);
	}
	
	public void select(By locator, int optionIndex) {
		new Select(findElement(locator)).selectByIndex(optionIndex);
	}

	public void selectRandom(By locator) throws Exception {
		Select select = new Select(driver.findElement(locator));
		List<WebElement> options = select.getOptions();
		if (options.size() == 0) {
			throw new Exception("Nothing to select in drop-down list!");
		} else {
			int index = new Random().nextInt(options.size());
			options.get(index).click();
		}
	}
	
	public void openURL(String string) {
		driver.get(manager.getProperty("baseUrl") + string);
	}
	
	public void openAbsoluteURL(String string) {
		driver.get(string);
	}
	

	protected void click(By locator) {
		findElement(locator).click();
	}

	public int getNumberOfElementsInDropDownList(By locator) {		
		Select select = new Select(driver.findElement(locator));
		List<WebElement> options = select.getOptions();
		return options.size();
	}

	public boolean isElementPresent(By locator) {
		driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
		boolean verdict = driver.findElements(locator).size() > 0;
	    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	    return verdict;
	}
	
	

}
